<?php
/**
 * Created by PhpStorm.
 * User: HuyNguyen
 * Date: 8/1/14
 * Time: 11:03 PM
 */

class ChangePasswordForm extends CFormModel
{
    public $currentPassword;
    public $newPassword;
    public $retypeNewPassword;
    private $_user;

    public function rules()
    {
        return array(
            array('currentPassword,newPassword,retypeNewPassword', 'required',),
             // password needs to be authenticated
            array('currentPassword', 'authenticate'),
        );
    }

    public function compareCurrentPassword($attribute,$params)
    {
        if( md5($this->currentPassword) !== $this->_user->password )
        {
            $this->addError($attribute,'Invalid current Password');
        }
    }

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute,$params)
    {
        if(!$this->hasErrors())
        {
            $hash = CPasswordHelper::hashPassword($this->currentPassword);
            $this->_user  = User::model()->findByAttributes(array("user_id" => Yii::app()->user->getId(), "status" => "ACTIVE"));
            if($this->_user == null)
                $this->addError('password',Yii::t('messages','User has been disabled.'));
            else{
                if(!CPasswordHelper::verifyPassword($this->currentPassword, $this->_user->password)){
                    $this->addError('password',Yii::t('messages','The password you entered is incorrect.'));
                }
            }
        }
    }

    public function attributeLabels()
    {
        return array(
            'currentPassword'=> Yii::t("messages","Current Password"),
            'newPassword'=> Yii::t("messages","New Password"),
            'retypeNewPassword'=> Yii::t("messages","Retype New Password"),
        );
    }

    public function changePassword()
    {
        $this->_user->password = $this->newPassword;
        if( $this->_user->save() )
            return true;
        return false;
    }
}